package Server.Login;

import Protobuf.ChatProto;
import Protobuf.DbProto;
import Server.Cache.MsgSession;
import Server.Common.Player;
import Server.Common.World;
import Server.DbClientHandler;
import Server.ServerHandler;

public class Register extends TransferMsg {

    /**发送注册数据到数据库服务器，由数据库服务器确认无误并存储成功后，返回玩家id*/
    @Override
    public void sendDbPacket(MsgSession session) {
        ChatProto.Msg msg = session.getMsg();
        ChatProto.Register register = msg.getRegister();
        String username = register.getUsername();
        String psd = register.getPsd();
        String name = register.getName();
        String channelId = session.getChannelId();
        if(World.getInstance().usernames.contains(username)){
            ChatProto.RespLogin.LoginResult type = ChatProto.RespLogin.LoginResult.usernameIsExist;
            ChatProto.Msg regSucMsg = ChatProto.Msg.newBuilder().setMsgType(ChatProto.Msg.MsgType.res)
                    .setRespLogin(ChatProto.RespLogin.newBuilder().setLoginResult(type).setSuc(false).build()).build();
            session.getChannel().writeAndFlush(regSucMsg);
            return;
        }
        DbProto.Msg retMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.res).setChannelId(channelId)
                .setPlayer(DbProto.Player.newBuilder().setUsername(username).setPsd(psd).setName(name).build()).build();
        DbClientHandler.getDbServerCtx().writeAndFlush(retMsg);
    }


    public void registration(DbProto.Msg msg){
        //如果账号存在，返回0，不存在则返回id自增值
        Long id = msg.getPlayer().getId();
        String username = msg.getPlayer().getUsername();
        boolean loginResult = false;
        ChatProto.RespLogin.LoginResult type;
        System.out.println(id+" "+username);
        if (id==0L) {
            type = ChatProto.RespLogin.LoginResult.usernameIsExist;
        } else {
            //注册成功后将用户信息存入缓存
            type = ChatProto.RespLogin.LoginResult.registerSuccess;
            Player player = Player.create(msg,id,username);
            player.load();
            loginResult = true;
        }
        loginResponse(type,loginResult, msg.getChannelId(),id,msg.getPlayer().getName());
        System.out.println("注册成功");
    }

}
